import axios from '@/utils/request'
import cache from './cache'
import Lockr from 'lockr'
import store from '@/store'
import Cookies from 'js-cookie'
import { getCookiesDomain } from '@/utils'
import { LOCAL_ADMIN_TOKEN, COOKIE_ADMIN_TOKEN } from '@/utils/constants.js'

/** 移除授权信息 */
export function removeAuth(props = { clearCookies: false }) {
  return new Promise((resolve, reject) => {
    // if (props.clearCookies) {
    //   Cookies.remove('User', { path: '/', domain: '.72crm.com' })
    // }
    cache.rmAxiosCache()
    store.commit('SET_ALLAUTH', null)
    delete axios.defaults.headers.common[LOCAL_ADMIN_TOKEN]
    resolve(true)
  })
}

/** 注入授权信息 */
export function addAuth(adminToken) {
  return new Promise((resolve, reject) => {
    axios.defaults.headers.common[LOCAL_ADMIN_TOKEN] = adminToken
    // store.dispatch('SystemLogoAndName')
    resolve(true)
  })
}

/** 获取授权信息 */
export function getAuth() {
  return new Promise((resolve, reject) => {
    // cookie 的优先级最高，与它不同的会被覆盖掉
    const cookieAdminToken = Cookies.get(COOKIE_ADMIN_TOKEN)
    const axiosAdminToken = axios.defaults.headers.common[LOCAL_ADMIN_TOKEN]
    if (axiosAdminToken) {
      // 本地cookie 存在，但与当前axios不一样，用cookie覆盖所有
      if (!!cookieAdminToken && axiosAdminToken !== cookieAdminToken) {
        cache.updateAxiosCache(cookieAdminToken)
      }
      resolve()
    } else {
      // if (Lockr.get(LOCAL_ADMIN_TOKEN) || Cookies.get('User')) {
      let lockAdminToken = Lockr.get(LOCAL_ADMIN_TOKEN)
      // 状态码 1007 下 会忽略下一次的cookies信息读取
      // 重点 数据以cookie为准，只要cookie有值，或者与Lockr不同，覆盖Lockr
      if (window.sessionStorage.wkIgnoreCookies !== true && !!cookieAdminToken && (lockAdminToken !== cookieAdminToken)) {
        Lockr.set(LOCAL_ADMIN_TOKEN, cookieAdminToken)
        lockAdminToken = cookieAdminToken
      }

      // 本地有lock
      if (!!lockAdminToken && !cookieAdminToken) {
        const domain = getCookiesDomain()
        Cookies.set(COOKIE_ADMIN_TOKEN, lockAdminToken, { domain: domain, expires: 365 })
      }

      if (lockAdminToken) {
        cache.updateAxiosCache()
        store.dispatch('GetUserInfo').then(() => {
          // 不忽略Cookies
          window.sessionStorage.wkIgnoreCookies = false

          // 获取 messageBox DOM 后移除
          var el_message_box = document.querySelector('.el-message-box__wrapper')
          var v_modal = document.querySelector('.v-modal')
          if (el_message_box && v_modal) {
            el_message_box.parentNode.removeChild(el_message_box)
            v_modal.parentNode.removeChild(v_modal)
          }
          resolve()
        }).catch(() => {
          reject()
        })
      } else {
        reject()
      }
    }
  })
}
